package com.hzit.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.common.utils.PageResult;
import com.hzit.entity.Classes;
import com.hzit.entity.Student;
import com.hzit.mapper.ClassesMapper;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import com.hzit.util.MySqlSessionFactory;
import com.hzit.vo.StudentVO;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
public class StudentServiceImpl implements StudentService {


	//1. 查询所有学生
	@Override
	public List<Student> findAll() throws IOException {
		try(SqlSession session = MySqlSessionFactory.getSqlSessoin(true)){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			return mapper.findAll();
		}
	}

	/**
	 * 2. 条件查询带分页
	 * @param page
	 * @param pageSize
	 * @param studentVO
	 * @return
	 */
	@Override
	public PageResult<Student> search(int page, int pageSize, StudentVO studentVO) throws IOException {
		//2.1 开始分页
		PageHelper.startPage(page,pageSize);
		// 2.2 开始分页查询
		try(SqlSession session = MySqlSessionFactory.getSqlSessoin(true)){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			ClassesMapper classesMapper = session.getMapper(ClassesMapper.class);
			// 2.3 开始分页查询并处理学生所在的班级名称字段
			List<Student> students = mapper.search(studentVO);
			for (Student student : students) {
				Classes classes = classesMapper.findById(student.getCid());
				student.setCname(classes.getCname());
			}

			// 2.4 将上面的students集合转换为Page<Student>集合
			Page<Student> studentPage = (Page<Student>) students;
			return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
		}
	}

	//3. 添加学生
	@Override
	public void add(Student student) throws IOException {
		try(SqlSession session = MySqlSessionFactory.getSqlSessoin(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.insert(student);
		}
	}

	//4. 修改学生
	@Override
	public void update(Student student) throws IOException {
		try(SqlSession session = MySqlSessionFactory.getSqlSessoin(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.update(student);
		}
	}

	//5. 根据学号删除学生
	@Override
	public void removeStudent(String sids) throws IOException {
		try(SqlSession session = MySqlSessionFactory.getSqlSessoin(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			List<String> ids = Arrays.asList(sids.split(","));
			mapper.removeStudent(ids);
		}
	}
}
